<?php

namespace app\common\model;

use think\Model;
use traits\model\SoftDelete;


class Shop extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'shop';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [
    ];

    const IS_SHOW_YES = 1; // 显示
    const IS_SHOW_NOT = 0; // 不显示

    const EARTH_RADIUS          = '6378.138'; // 地球半径

    protected static function init()
    {
//        self::afterInsert(function ($row) {
//            $pk = $row->getPk();
//            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
//        });
    }

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id')->setEagerlyType(0);
    }
    public function clock()
    {
        return $this->belongsTo('Clock', 'id', 'shop_id', [], 'left')->setEagerlyType(0);
    }

    public static function getListPage($conditions = [], $fields = ['shop.*,audit.phone_name,audit.phone,audit.type as shop_type'], $order = 'shop.weigh desc,shop.id desc')
    {
        $model = self::alias('shop')
            ->join('User user', 'shop.user_id = user.id')
            ->join('UserShopAudit audit', 'shop.user_id = audit.user_id')
            ->whereNull('audit.delete_time')
            ->where('user.status', 'normal');

        $lat = isset($conditions['lat']) ? (empty($conditions['lat']) ? 0 : $conditions['lat']) : 0;
        $lng = isset($conditions['lng']) ? (empty($conditions['lng']) ? 0 : $conditions['lng']) : 0;
//        $order = 'shop.weigh desc,shop.id desc';
        $limit = isset($conditions['limit']) ? $conditions['limit'] : 10;

        $order_1 = '';
        if(isset($conditions['top']) && $conditions['top']){
            $order_1 = 'shop.is_top desc,';
        }
        if ($lat && $lng) {
            $fields[] = 'ROUND(' . self::EARTH_RADIUS . ' * 2 * ASIN(SQRT(POW(SIN((' . $lat . ' * PI() / 180 - shop.lat * PI() / 180) / 2), 2) + COS(' . $lat . ' * PI() / 180) * COS(shop.lat * PI() / 180) * POW(SIN((' . $lng . ' * PI() / 180 - shop.lng * PI() / 180) / 2), 2))) * 1000) AS juli';
            $order_1 = $order_1.'juli asc,';
            if(isset($conditions['map_m']) && !empty($conditions['map_m'])){
                $juli_sql = 'ROUND(' . self::EARTH_RADIUS . ' * 2 * ASIN(SQRT(POW(SIN((' . $lat . ' * PI() / 180 - shop.lat * PI() / 180) / 2), 2) + COS(' . $lat . ' * PI() / 180) * COS(shop.lat * PI() / 180) * POW(SIN((' . $lng . ' * PI() / 180 - shop.lng * PI() / 180) / 2), 2))) * 1000) <= '.$conditions['map_m'];
                $model->where($juli_sql);
            }
        }
        $order = $order_1.$order;
        if (isset($conditions['is_show']) && !empty($conditions['is_show'])) {
            $model->where('shop.is_show', $conditions['is_show']);
        }
        if (isset($conditions['province_id']) && !empty($conditions['province_id'])) {
            $model->where('shop.province_id', $conditions['province_id']);
        }
        if (isset($conditions['city_id']) && !empty($conditions['city_id'])) {
            $model->where('shop.city_id', $conditions['city_id']);
        }
        if (isset($conditions['area_id']) && !empty($conditions['area_id'])) {
            $model->where('shop.area_id', $conditions['area_id']);
        }
        if (isset($conditions['street_id']) && !empty($conditions['street_id'])) {
            $model->where('shop.street_id', $conditions['street_id']);
        }
        if (isset($conditions['circle_id']) && !empty($conditions['circle_id'])) {
            $model->where('shop.circle_id', $conditions['circle_id']);
        }
        // 2022-09-20 添加行业
        if (isset($conditions['industry_id']) && !empty($conditions['industry_id'])) {
            $model->where('audit.industry_id', $conditions['industry_id']);
        }
        if (isset($conditions['keywords']) && !empty($conditions['keywords'])) {
            $model->where('shop.name', 'like', "%" . $conditions['keywords'] . "%");
        }
        if (isset($conditions['self']) && !empty($conditions['self'])) {
//            $model->where('shop.user_id', 'neq', $conditions['self']);
        }
        if (isset($conditions['user_id']) && !empty($conditions['user_id'])) {
            $model->where('shop.user_id', $conditions['user_id']);
        }
        // 我的
        if (isset($conditions['my']) && !empty($conditions['my'])) {
            $model->where('shop.user_id', $conditions['my']);
        }else{
            $model->where('audit.status', ShopAudit::STATUS_AUDIT_PASS)
                ->where('audit.expiration_time', '>', time());
        }

        $model->field($fields)->order($order)->group('shop.id');

        $is_page = true;
        if(isset($conditions['not_page']) && $conditions['not_page']){
            $is_page = false;
        }
        if($is_page){
            $list = $model->paginate($limit);
        }else{
            $list = $model->select();
        }
        $typeArray = ShopAudit::getTypeArray();
        // 获取排行榜开始结束时间
        $rank_time_where = Config::getClockTime();
        foreach ($list as $key => &$value) {
            $value['logo'] = getRealImg($value['logo']);
//            $flag = model('ShopFlag')->where('id', 'in', $value['flag'])->order('weigh desc,id desc')->column('name');
            $value['flag'] = explode(",", $value['flag']);
            $value['user_name'] = '';
            $value['shop_type_name'] = '';
            $value['is_self'] = 0;
            if($value['user_id']){
                if (isset($conditions['self']) && !empty($conditions['self'])) {
                    if($value['user_id'] == $conditions['self']){
                        $value['is_self'] = 1;
                    }
                }
            }
            $value['province_name'] = District::where('id', $value['province_id'])->value('name') ?: '';
            $value['city_name'] = District::where('id', $value['city_id'])->value('name') ?: '';
            $value['area_name'] = District::where('id', $value['area_id'])->value('name') ?: '';
            $value['store_area_name'] = District::where('id', $value['store_area_id'])->value('shop_name') ?: '';
            $value['street_name'] = District::where('id', $value['street_id'])->value('name') ?: '';
            $value['industry_name'] = Industry::where('id', $value['industry_id'])->value('name') ?: '';
            $value['circle_name'] = Circle::where('id', $value['circle_id'])->value('name') ?: '';
            $value['shop_type_name'] = $typeArray[$value['shop_type']];
            $juli = isset($value['juli']) ? $value['juli'] : 0;
            $value['juli'] =  '0m';
            // 排行
            $count = Clock::alias('c')->where('c.shop_id', $value['id'])->where($rank_time_where)->count();
            $value['clock_number'] = $count;
            $new_clock = Clock::alias('c')->where('c.shop_id', $value['id'])->where($rank_time_where)->field('createtime')->order('c.createtime desc')->find();
            $value['rank'] = 0;
            if($count){
                $rank = Clock::alias('c')->join('Shop s', 'c.shop_id = s.id')->whereNull('s.delete_time')->where($rank_time_where)->group('c.shop_id')->having('count(*) > '.$count)->select();
                $count1 = Clock::alias('c')->join('Shop s', 'c.shop_id = s.id')->whereNull('s.delete_time')->where($rank_time_where)->where('c.createtime', '<', $new_clock['createtime'])->group('c.shop_id')->having('count(*) = '.$count)->select();
                $value['rank'] = count($rank) + count($count1) + 1;
            }

            if ($juli > 1000) {
                $value['juli'] = round(($juli / 1000), 2) . 'km';
            } else {
                $value['juli'] = $juli . 'm';
            }
            $value['vip_tage'] = number_format($value['vip_tage']/10, 2, '.', '') - 0;

            unset($value['type']);
            unset($value['province_id']);
            unset($value['city_id']);
            unset($value['area_id']);
            unset($value['store_area_id']);
            unset($value['street_id']);
            unset($value['createtime']);
            unset($value['delete_time']);
            unset($value['store_id']);
            unset($value['circle_id']);
            unset($value['industry_id']);
            unset($value['weigh']);
//            unset($value['is_show']);
            unset($value['user_id']);
        }
        return $list;
    }

    public function getInfo($id, $fields = ['shop.*,audit.phone_name,audit.phone,audit.type as shop_type'], $user_id = 0){
        $value = self::alias('shop')
            ->join('User user', 'shop.user_id = user.id')
//            ->join('UserShopAudit auditaudit', 'shop.user_id = audit.user_id')
//            ->whereNull('audit.delete_time')
//            ->where('audit.status', ShopAudit::STATUS_AUDIT_PASS)
//            ->where('audit.expiration_time', '>', time())
            ->where('shop.id', $id)
            ->field($fields)
            ->find();

        $audit = ShopAudit::where('user_id', $value['user_id'])->order('id desc')->find();

        $value['shop_type'] = $audit['type'];
        $value['phone_name'] = $audit['phone_name'];
        $value['phone'] = $audit['phone'];
        $value['industry_name'] = District::where('id', $audit['industry_id'])->value('name') ?: '';
        if($user_id != $value['user_id'] && $user_id != 0){
            if($value['is_show'] == self::IS_SHOW_NOT){
                $this->error = "该商铺已关闭";
                return false;
            }
            if($audit['status'] != ShopAudit::STATUS_AUDIT_PASS){
                $this->error = "该商铺已关闭";
                return false;
            }
            if($audit['expiration_time'] <= time()){
                $this->error = "该商铺已关闭";
                return false;
            }
        }

        if($value['user_status'] != 'normal'){
            $this->error = "该商铺已关闭";
            return false;
        }
        unset($value['user_status']);
        $typeArray = ShopAudit::getTypeArray();
        $value['logo_show'] = getRealImg($value['logo']);
//        $flag = model('ShopFlag')->where('id', 'in', $value['flag'])->order('weigh desc,id desc')->column('name');
//        $value['flag'] = explode(",", $value['flag']);
        $value['flag_show'] = explode(",", $value['flag']);
        $value['shop_type_name'] = '';
        $value['is_self'] = 0;
        $value['is_clock'] = 0;
        if($user_id){
            if($value['user_id'] == $user_id){
                $value['is_self'] = 1;
            }
            if(Clock::where('user_id', $user_id)->where('shop_id', $id)->where('createtime', 'BETWEEN', [strtotime(date("Y-m-d")), strtotime(date("Y-m-d 23:59:59"))])->count()){
                $value['is_clock'] = 1;
            }
        }
        $value['province_name'] = District::where('id', $value['province_id'])->value('name') ?: '';
        $value['city_name'] = District::where('id', $value['city_id'])->value('name') ?: '';
        $value['area_name'] = District::where('id', $value['store_area_id'])->value('name') ?: '';
        $value['shop_area_name'] = District::where('id', $value['area_id'])->value('shop_name') ?: '';
        $value['street_name'] = District::where('id', $value['street_id'])->value('name') ?: '';
        $value['store_name'] = Store::where('id', $value['store_id'])->value('name') ?: '';
        $value['circle_name'] = Circle::where('id', $value['circle_id'])->value('name') ?: '';
        $value['shop_type_name'] = $typeArray[$value['shop_type']];
        $images = explode(',', $value['images']);
//        unset($value['images']);
        $info_images = [];
        $more_images = [];
        foreach($images as $k => $v){
            if($k > 2){
                array_push($more_images, getRealImg($v));
            }else{
                array_push($info_images, getRealImg($v));
            }
        }
        $value['info_images'] = $info_images;
        $value['more_images'] = $more_images;

        $value['image_show'] = getRealImg($value['image']);
        $value['introduce_show'] = replace_editor_content_images_url($value['introduce']);

        // 获取排行榜开始结束时间
        $rank_time_where = Config::getClockTime();
        // 排行
        $count = Clock::alias('c')->where('c.shop_id', $value['id'])->where($rank_time_where)->count();
        $value['clock_number'] = $count;
        $new_clock = Clock::alias('c')->where('c.shop_id', $value['id'])->where($rank_time_where)->field('createtime')->order('createtime desc')->find();
        $value['rank'] = 0;
        if($count){
            $rank = Clock::alias('c')->join('Shop s', 'c.shop_id = s.id')->whereNull('s.delete_time')->where($rank_time_where)->group('c.shop_id')->having('count(*) > '.$count)->select();
            $count1 = Clock::alias('c')->join('Shop s', 'c.shop_id = s.id')->whereNull('s.delete_time')->where($rank_time_where)->where('c.createtime', '<', $new_clock['createtime'])->group('c.shop_id')->having('count(*) = '.$count)->select();
            $value['rank'] = count($rank) + count($count1) + 1;
        }

        if(isset($value['juli'])){
            if ($value['juli'] > 1000) {
                $value['juli_text'] = round(($value['juli'] / 1000), 2) . '千米';
            } else {
                $value['juli_text'] = $value['juli'] . '米';
            }
        }
        $value['vip_tage'] = number_format($value['vip_tage']/10, 2, '.', '') - 0;

        unset($value['user_id']);
        unset($value['store_area_id']);
        unset($value['industry_id']);
//        unset($value['area_id']);
//        unset($value['store_id']);
//        unset($value['street_id']);
//        unset($value['circle_id']);
//        unset($value['is_show']);
        unset($value['status']);
        unset($value['expiration_time']);

        return $value;
    }
}
